<template>
  <view>
    <HeaderNavTabarVue title="拜访列表" />
    <view class="topClass">
      <uni-search-bar
        v-model="searchValue"
        cancelButton="none"
        class="searchBar"
        clearButton="auto"
        placeholder="请输入客户名称"
        radius="8rpx"
        @input="searchPerson"
      />
      <uni-segmented-control
        :current="current"
        :values="items2"
        active-color="#165DFF"
        class="segment"
        in-active-color="#4E5969"
        style-type="text"
        @clickItem="onClickItem"
      />
    </view>
    <view class="uv-empty" v-if="cardDataList.length === 0">
      <uv-empty :text="emptyText" icon="../../static/images/empty.png"></uv-empty>
    </view>
    <scroll-view
      v-else
      :style="`height: calc(100vh - ${getTitleBarHeight() * 2}rpx - 120rpx - 56rpx - 40rpx )`"
      class="scroll-Y"
      scroll-y="true"
      :lower-threshold="50"
      @scrolltolower="scrolltolower"
    >
      <checkbox-group @change="checkboxChange">
        <label
          v-for="(item, index) in cardDataList"
          :key="index"
          :class="isApplyPage ? 'uni-list-cell uni-list-cell-pd card-list' : ''"
        >
          <view v-if="isApplyPage">
            <checkbox :checked="item.checked" :value="item" />
          </view>
          <view :class="isApplyPage ? 'card-item card-item2' : 'card-item'" @click="toDetail(item)">
            <view class="contentContainer">
              <view class="content content2">
                <view class="left">
                  <text class="titleText">{{ item.customerName }}</text>
                </view>
                <p :class="item.underwayOutcome">
                  {{ item.underwayOutcome }}
                </p>
              </view>
              <view class="content">
                <text class="contentTitle">地址</text>
                <text class="contentTitle">：</text>
                <text class="contentText">{{ item.address }}</text>
              </view>
              <view class="content" v-if="isApplyPage">
                <text class="contentTitle">客户拜访ID</text>
                <text class="contentTitle">：</text>
                <text class="contentText">{{ item.id }}</text>
              </view>
              <view class="content" v-if="item.underwayOutcome === '跟进中'">
                <text class="contentTitle">跟进时间</text>
                <text class="contentTitle">：</text>
                <text class="contentText"
                  >{{ dayjs(item.underwayTime).format('YYYY-MM-DD HH:mm') }}
                </text>
              </view>
              <view class="content" v-if="item.underwayOutcome === '已完成'">
                <text class="contentTitle">完成时间</text>
                <text class="contentTitle">：</text>
                <text class="contentText">{{ dayjs(item.underwayTime).format('YYYY-MM-DD') }}</text>
              </view>
            </view>
            <view class="contentContainer"></view>
            <view class="info">
              <image
                :src="baseUrl + item.avatar"
                style="width: 36rpx; height: 36rpx; margin-right: 8rpx; border-radius: 50%"
              >
              </image>
              <text class="nameText">{{ item.nickName }}</text>
              <span style="flex-grow: 1"></span>
              <text class="timeText">{{ dayjs(item.updateTime).format('YYYY-MM-DD HH:mm') }} </text>
            </view>
          </view>
        </label>
      </checkbox-group>
      <view class="buttonContainer" v-if="isApplyPage">
        <text>{{ tipsValue }}</text>
        <p class="buttonClass" @tap="handleClick">确定</p>
      </view>
    </scroll-view>
  </view>
  <view v-show="statusLoding" class="animbox-scroll-loading">
    <view></view>
    <view></view>
    <view></view>
    <view></view>
    <view></view>
  </view>
</template>

<script setup>
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { defineProps, onMounted, ref } from 'vue'
import HeaderNavTabarVue from '@/components/HeaderNavTabar/HeaderNavTabar.vue'
import { getTitleBarHeight } from '@/utils/system.js'
import AuditCard from '@/components/audit/AuditCard.vue'
import dayjs from 'dayjs'
import {
  getAttendanceApplyApi,
  getSelectApproveCount,
  getSelectApproveList,
  listFinancialApplyControllerApi,
} from '@/api/attendance'
import { getUserProfile } from '@/api/system/user'
import { getNewVisitListApi, getVisitListApi } from '@/api/visit.js'

const emptyText = ref('数据请求中...')
const showBottonNaviBar = ref(true)
const removeBottomNaviBar = (val) => {
  showBottonNaviBar.value = val
}
const props = defineProps(['id'])
const isApplyPage = ref(null) // 是否是申请页面过来
const customerId = ref(null) // 客户id
const searchValue = ref(null)
const index = ref(0)
let pageNum = ref(1)
let pageSize = ref(10)
let totals = ref(888)
let statusLoding = ref(false)
const baoxiaoDataList = ref([]) // 报销列表
const tipsValue = ref('请选择对应拜访记录')

const tabChange = (e) => {
  index.value = e
}

//顶部分段器
const items2 = ref(['全部', '跟进中', '已完成'])
const current = ref(0)
const typeGenJin = ref('') // 全部‘’ 跟进中 已完成

const updatedCard = async () => {
  await typeChange()
}
const userId = ref(null)
const cardDataList = ref([])

const onClickItem = (e) => {
  typeGenJin.value = e.currentIndex
  typeChange()
}

const gotoDetailPage = (item) => {
  console.log('gotoDetailPage')
}

const getUserProfileFn = async () => {
  let { code, data } = await getUserProfile()
  if (code === 200) {
    userId.value = data.userId
  }
}

// 分页接口对接
const typeChange = async (flag) => {
  // 调取筛选
  let params = {
    underwayOutcome:
      Number(typeGenJin.value) === 1 ? '跟进中' : Number(typeGenJin.value) === 2 ? '已完成' : '',
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    userId: userId.value,
    customerName: searchPersonData.value,
  }
  console.log(params, ' params')

  if (isApplyPage.value) {
    params.customerId = customerId.value
  }

  let API = isApplyPage.value ? getVisitListApi : getNewVisitListApi

  let { rows, code, total } = await API(params)
  try {
    if (code === 200) {
      if (statusLoding.value) {
        statusLoding.value = false //加载中状态
      }
      if (flag) {
        cardDataList.value = [...cardDataList.value, ...rows]
      } else {
        cardDataList.value = rows
      }
      totals.value = total

      if (cardDataList.value.length === 0) {
        emptyText.value = '列表为空'
      }
    }
  } catch {}
}

const scrolltolower = async () => {
  statusLoding.value = true //加载完状态
  let allTotal = pageNum.value * pageSize.value
  if (allTotal < totals.value) {
    pageNum.value++
    typeChange(true)
  } else {
    uni.showToast({
      title: '数据加载完毕',
    })
    statusLoding.value = false
  }
}

onPullDownRefresh(async () => {
  pageNum.value = 1
  await typeChange(false)
  // 关闭下拉刷新
  uni.stopPullDownRefresh()
})
const searchPersonData = ref(null)

function debounce(func, wait) {
  let timeout
  return function (...args) {
    const context = this
    clearTimeout(timeout)
    timeout = setTimeout(() => func.apply(context, args), wait)
  }
}

let debounceSearch = debounce(function () {
  pageNum.value = 1
  pageSize.value = 10
  typeChange()
}, 500)

const searchPerson = (v) => {
  searchPersonData.value = v
  // 掉搜索接口
  debounceSearch()
}

// 跳转详情
const toDetail = (item) => {
  // status 1 申请拜访 2 跟进状态详情 3 历史记录详情
  if (!isApplyPage.value) {
    uni.navigateTo({
      url: '/pages/visit/customerVisit?status=2&item=' + JSON.stringify(item),
    })
  }
}

const visitData = ref(null)
const checkboxChange = (e) => {
  visitData.value = e.detail.value
  if (e.detail.value.length > 0) {
    tipsValue.value = visitData.value[0].customerName + visitData.value[0].id
  } else {
    tipsValue.value = '请选择对应拜访记录'
  }
}

// 获取申请列表 已申请过的客户拜访数据 不能再次申请报销
const listFinancialApplyControllerApiFn = async () => {
  let params = {
    type: '油费报销申请',
  }
  let { code, rows } = await listFinancialApplyControllerApi(params)
  if (code == 200) {
    baoxiaoDataList.value = rows
  }
}

const handleClick = () => {
  if (visitData.value.length > 1) {
    uni.showToast({
      title: '每次只能选择一个拜访记录',
      icon: 'none',
    })
  } else if (baoxiaoDataList.value.some((item) => item.applyId === visitData.value[0].id)) {
    uni.showToast({
      title: '您已申请过当前拜访报销,不能再次申请',
      icon: 'none',
    })
    return
  } else {
    uni.navigateBack({
      delta: 1,
      success: function () {
        uni.$emit('getVisitData', visitData.value)
      },
    })
  }
}

onShow(async () => {
  await getUserProfileFn()
  await typeChange(false)
  await listFinancialApplyControllerApiFn()
})

onLoad(async (options) => {
  isApplyPage.value = options?.isApplyPage
  customerId.value = options?.customerId
})
</script>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

:deep(.uni-checkbox-input) {
  border-radius: 50%;
}

.card-list {
  @include flex($align: center);
  background-color: #fff;
  padding: 0 $spacing-row-base;
}

.buttonContainer {
  position: fixed;
  bottom: 0;
  right: 0;
  z-index: 999;
  height: 130rpx;
  width: 100%;
  background-color: #f7f8fa;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;

  .buttonClass {
    text-align: center;
    color: #165dff;
    z-index: 999;
    font-size: 28rpx;
  }
}

body {
  background-color: $uni-bai;
  overflow: hidden;
}

.searchBar {
  height: 120rpx;
}

.segment {
  height: 56rpx;
  padding-bottom: 12rpx;
}

.topClass {
  background-color: #fff;
}

:deep(.zb-dropdown-menu__bar) {
  height: 100% !important;
  box-shadow: none !important;
}

.dropDownItem {
  border: #e5e6eb 1px solid;
  border-radius: 44rpx;
  width: 335rpx;
  height: 64rpx;
}

:deep(.uni-searchbar__box) {
  justify-content: left;
}

.card-item {
  background-color: #fff;
  border-radius: 16rpx;
  border: 1rpx solid var(---line-1, #e5e6eb);
  background: #fff;
  margin: 32rpx;
  padding-top: 24rpx;
}

.card-item2 {
  width: 100%;
}

.跟进中 {
  color: #ff7d00;
  border-radius: 4rpx;
  background: var(---warning-1, #fff7e8);
  font-size: 24rpx;
  padding: 4rpx 8rpx;
}

.已完成 {
  color: #00b42a;
  border-radius: 4rpx;
  background: var(---success-1, #e8ffea);
  padding: 4rpx 8rpx;
  font-size: 24rpx;
}

.title {
  display: flex;
  align-items: stretch;
  //justify-content: space-between;
  align-items: center;
  padding-left: 24rpx;
  padding-right: 24rpx;
}

.titleText {
  color: #1d2129;
  font-family: 'PingFang SC';
  font-size: 32rpx;
  font-style: normal;
  font-weight: 500;
  line-height: 44.8rpx;
}

.contentContainer {
  padding-left: 24rpx;
  padding-right: 24rpx;
}

.content2 {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    width: 80%;
  }
}

.content {
  margin-top: 16rpx;
}

.contentTitle {
  color: #86909c;
  font-family: 'PingFang SC';
  font-size: 28rpx;
  font-style: normal;
  font-weight: 400;
  line-height: 39.2rpx;
}

.contentText {
  color: #1d2129;
  font-family: 'PingFang SC';
  font-size: 28rpx;
  font-style: normal;
  font-weight: 400;
  line-height: 39.2rpx;
}

.info {
  display: flex;
  align-items: stretch;
  //justify-content: space-between;
  align-items: center;
  margin-top: 16rpx;
  padding-left: 24rpx;
  padding-right: 24rpx;
  margin-bottom: 16rpx;
}

.nameText {
  color: #4e5969;
  text-align: center;
  font-family: 'PingFang SC';
  font-size: 24rpx;
  font-style: normal;
  font-weight: 400;
  line-height: 33.6rpx;
}

.timeText {
  color: #86909c;
  text-align: right;
  font-family: 'PingFang SC';
  font-size: 24rpx;
  font-style: normal;
  font-weight: 400;
  line-height: 33.6rpx;
}
</style>
